package com.mar.tech.unify;

import com.mar.tech.unify.factory.UnifyFactory;
import com.mar.tech.unify.http.HttpVerticle;
import io.vertx.config.ConfigRetriever;
import io.vertx.config.ConfigRetrieverOptions;
import io.vertx.config.ConfigStoreOptions;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * Description: 启动Verticle .<br>
 *
 * @author jm
 * @since 2020/4/2
 */
public class MainVerticle extends AbstractVerticle {
  private final static Logger logger = LoggerFactory.getLogger(MainVerticle.class);
  private ConfigRetriever retriever = null;

  @Override
  public void start(Promise<Void> promise) throws Exception {
    ConfigRetrieverOptions options = configOptions();
    retriever = ConfigRetriever.create(vertx, options);
    retriever.getConfig(ar -> {
      if (ar.failed()) {
        logger.error("读取配置失败", ar.cause());
        return;
      }
      final JsonObject config = ar.result();
      logger.debug("全局配置文件:{}", config.encodePrettily());
      UnifyFactory.init(vertx.getOrCreateContext(), config);
      vertx.deployVerticle(new HttpVerticle(), new DeploymentOptions().setConfig(config));
    });
    vertx.exceptionHandler(ar -> {
      logger.error("[Vert.x] - [未捕获的异常]", ar);
    });
  }

  /**
   * 拉去本地配置.
   *
   * @return
   */
  private ConfigRetrieverOptions configOptions() {
    ConfigRetrieverOptions options = new ConfigRetrieverOptions()
      .setIncludeDefaultStores(true)
      .setScanPeriod(-1);
    Arrays.asList("verticles.json", "sql.json")
      .forEach(filePath -> {
        options.addStore(
          new ConfigStoreOptions()
            .setType("file")
            .setFormat("json")
            .setOptional(true)
            .setConfig(new JsonObject().put("path", filePath))
        );
      });
    options.getStores().forEach(store -> {
      store.getConfig().put("cache", "false");
    });
    return options;
  }

  @Override
  public void stop() throws Exception {
    if (retriever != null) {
      retriever.close();
    }
    super.stop();
  }
}
